package com.nblog.service;

import java.util.ArrayList;
import java.util.Date;

import java.util.List;
import com.google.common.collect.Lists;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;

import com.jfinal.plugin.activerecord.Page;
import com.nblog.cache.CacheClearUtils;
import com.nblog.constant.ApiConstant;
import com.nblog.model.SysRes;
import com.nblog.model.SysRole;
import com.nblog.model.SysRoleRes;
import com.nblog.plugin.ioc.annotation.JFService;
import com.nblog.resp.ApiResp;
import com.nblog.utils.CommonUtils;
import com.nblog.view.InvokeResult;
import com.nblog.view.ZtreeView;

@SuppressWarnings("serial")
@JFService
public class SysRoleService{
	public List<SysRole> getSysRoleList(int uid){
		
		return SysRole.dao.find("select * from sys_role where id in(select role_id from sys_user_role where user_id =?)",uid);
	}
	
	public List<SysRole> getSysRoleIdList(int uid){
		return SysRole.dao.find("select id from sys_role where id in(select role_id from sys_user_role where user_id =?)",uid);
	}
	
	public InvokeResult setVisible(String idStrs, Integer visible) {
		List<Integer> ids=CommonUtils.getIntegerListByStrs(idStrs);
		if(ids.contains(1)){
			return InvokeResult.failure("超级管理员不能被修改");
		}
		List<SysRole> modelList=new ArrayList<SysRole>();
		for(int id:ids){
			SysRole sysRole=new SysRole();
			sysRole.setId(id);
			sysRole.setStatus(visible);
			modelList.add(sysRole);
		}
		Db.batchUpdate(modelList, modelList.size());
		return InvokeResult.success("设置成功");
	} 

	public InvokeResult getZtreeViewList(Integer type, Integer roleId) {
		List<SysRes> curMenulist=this.getSysMenus(roleId);
		List<ZtreeView> ztreeViews=new ArrayList<ZtreeView>();
		ztreeViews.add(new ZtreeView(10000,null,"资源列表",true));
		for(SysRes SysRes : curMenulist){
			ZtreeView ztreeView=new ZtreeView();
			ztreeView.setId(SysRes.getInt("id"));
			ztreeView.setName(SysRes.getStr("name"));
			ztreeView.setOpen(true);
			if(SysRes.getInt("pid")==null){
				ztreeView.setpId(10000);
			}else{
				ztreeView.setpId(SysRes.getInt("pid"));
			}
			ztreeView.setChecked(SysRes.getLong("selected")==1?true:false);
			ztreeViews.add(ztreeView);
		}
		return InvokeResult.success(JsonKit.toJson(ztreeViews));
	}
	
	public InvokeResult getRoleZtreeViewList(Integer uid) {
		List<SysRole> list=this.getSysRoles(uid);
		List<ZtreeView> ztreeViews=new ArrayList<ZtreeView>();
		ztreeViews.add(new ZtreeView(10000,null,"角色列表",true));
		for(SysRole role : list){
			ZtreeView ztreeView=new ZtreeView();
			ztreeView.setId(role.getId());
			ztreeView.setName(role.getName());
			ztreeView.setOpen(true);
			ztreeView.setpId(10000);
			ztreeView.setChecked(role.getLong("selected")==1?true:false);
			ztreeViews.add(ztreeView);
		}
		return InvokeResult.success(JsonKit.toJson(ztreeViews));
	}
	
	public List<SysRes> getSysMenus(Integer roleId) {
		SysRole role=SysRole.dao.findById(roleId); 
		if(role!=null){
			List<SysRes> list=SysRes.dao.find("SELECT *,(CASE WHEN re.id IN (SELECT rr.res_id from sys_role_res rr WHERE rr.role_id="+roleId+" ) THEN 1 ELSE 0 END) as selected FROM sys_res re where re.enabled=1");
			return list;
		}
		return Lists.newArrayList();
	}
	public List<SysRole> getSysRoles(Integer uid) {
		List<SysRole> list=SysRole.dao.find("SELECT *,(CASE WHEN re.id IN (SELECT rr.role_id from sys_user_role rr WHERE rr.user_id="+uid+" ) THEN 1 ELSE 0 END) as selected FROM sys_role re where re.status=1");
		return list;
	}
	
	public InvokeResult saveMenuAssign(String menuIds, Integer roleId) {
		if(roleId.equals(1)){
			return InvokeResult.failure("超级管理员不能被修改");
		}
		Db.update("delete from sys_role_res where role_id = ?", roleId);
		if(CommonUtils.isNotEmpty(menuIds)){//改成批量插入
			List<String> sqlList=Lists.newArrayList();
			for(String id : menuIds.split(",")){
				if(CommonUtils.isNotEmpty(id)){
					if(!Integer.valueOf(id).equals(10000))
						sqlList.add("insert into sys_role_res (role_id,res_id) values ("+roleId+","+Integer.valueOf(id)+")");
				}
			}
			Db.batch(sqlList, 50);
			CacheClearUtils.clearUserMenuCache();
		}
		return InvokeResult.success();
	}
	
	public ApiResp save(Integer id, String name, String des) {
		ApiResp resp=new ApiResp();
		resp.setCode(ApiConstant.CODE_SUCCESS);
		if(id!=null){
			SysRole role=SysRole.dao.findById(id);
			role.set("name", name).set("des",des).update();
			resp.setMsg("编辑成功");
		}else{
			new SysRole().set("name", name).set("des",des).set("createdate", new Date()).save();
			resp.setMsg("添加成功");
		}
		return resp;
	} 
	
	public List<SysRole> getSysRoleNamelist(){
		return SysRole.dao.find("select id,name from sys_role where status = 1");
	}
	
	public String getRoleNames(String roleIds){
		String sql="select group_concat(name) as roleNames from sys_role where id in("+roleIds+")";
		SysRole sysRole=SysRole.dao.findFirst(sql);
		if(sysRole!=null){
			return sysRole.getStr("roleNames");
		}
		return "";
	}

	public Page<SysRole> getPage(int page, int rows, String name, String orderstr) {
		if(name!=null&&!name.equals("")){
			return SysRole.dao.paginate(page, rows, "select * from sys_role where name like '%?%' orderstr",name);
		}else{
			return SysRole.dao.paginate(page, rows, "select * ","from sys_role orderstr");
		}
	}

	public ApiResp del(String idStrs){
		List<Integer> ids=CommonUtils.getIntegerListByStrs(idStrs);
		for(Integer id:ids){
			Db.delete("delete from sys_role_res where role_id=?", id);
			SysRole.dao.deleteById(id);
		}
		ApiResp resp=new ApiResp();
		resp.setCode(ApiConstant.CODE_SUCCESS);
		resp.setMsg("删除成功");
		return resp;
	}
}
